package lc20240606;

import lc20240605.GeneSequence;

import java.util.*;

public class WordList {
    public static void main(String[] args) {
        WordList word = new WordList();
        List<String> list = new ArrayList<>(Arrays.asList("ymann","yycrj","oecij","ymcnj","yzcrj","yycij","xecij","yecij","ymanj","yzcnj","ymain"));

        int res = word.ladderLength("ymain", "oecij", list);
        System.out.println(res);
    }

    public int ladderLength(String beginWord, String endWord, List<String> wordList) {
        if (!wordList.contains(endWord)) {
            return 0;
        }

        Set<String> wordSet=new HashSet<>(wordList);
        Queue<String> queue = new LinkedList<>();
        queue.offer(beginWord);
        Set<String> visited = new HashSet<>();
        visited.add(beginWord);
        int count = 1;
        while (!queue.isEmpty()) {
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                String cur = queue.poll();
                if (cur.equals(endWord)) {
                    return count;
                }
                char[] curArray = cur.toCharArray();
                for (int index = 0; index < curArray.length; index++) {
                    char origin=curArray[index];
                    for (char j = 'a'; j <= 'z'; j++) {

                        if (j == curArray[index]) {
                            continue;
                        }
                        curArray[index] = j;
                        String newStr = new String(curArray);
                        if (wordSet.contains(newStr) && !visited.contains(newStr)) {
                            queue.add(newStr);
                            visited.add(newStr);
                            wordSet.remove(newStr); // 避免重复访问
                        }
                    }
                    curArray[index]=origin;
                }
            }
            count++;
        }
        return 0;
    }
}
